package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.User;

import cmput391.src.queries.*;

/**
 * Servlet implementation class CheckUsername
 */
@WebServlet("/CheckUsername")
public class CheckUsername extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckUsername() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = (request.getParameter("username")).trim();
		
		DBConnector dbConnect = new DBConnector();
		SecurityQueries security = null;
		
		try {
			security = new SecurityQueries(dbConnect.getConnection());
			UserManagementQueries umq = new UserManagementQueries(dbConnect.getConnection(), security);
			
			User user = umq.retrieveUserData(username);
			
			//This is a duplicate username, so do not allow it.
			if (user.getUserName().equals(username)) {
				response.getWriter().write("false");				
			}
			
			//We really shouldn't make it into this block, but it's here just in case.
			else {
				response.getWriter().write("true");					
			}
			response.setHeader("Cache-Control", "no-cache");
			//request.getRequestDispatcher("admin.jsp").forward(request, response);	
		}
		
		//An exception means the username is not taken.
		catch (Exception e) {
			response.getWriter().write("true");	
			//request.getRequestDispatcher("admin.jsp").forward(request, response);				
		}
	}

}
